<!--
 * @author luguoxiang
 * @date 2022/9/17
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <edit-container ref="containerRef" header="分配数据权限" width="1200px" destroy-on-close @confirm="submit">
    <lg-auto-size>
      <table class="gl-table" style="flex: 0">
        <tr class="gl-table-header">
          <th style="width: 60px">序号</th>
          <th style="width: 180px">资源</th>
          <th>
            数据规则：
            <t-radio-group size="small" default-value="">
              <t-radio v-for="x in rules" :key="x.id" :value="x.id" @click="setAll(x)">{{ x.name }}</t-radio>
            </t-radio-group>
          </th>
        </tr>
        <template v-if="resources.length">
          <tr v-for="(r, index) in resources" :key="r.key">
            <td>{{ index + 1 }}</td>
            <td>{{ r.name }}</td>
            <td>
              <t-radio-group v-model="selection[r.id]" size="small" default-value="">
                <t-radio v-for="x in r.rules" :key="x.id" :value="x.id" allow-uncheck>{{ x.name }}</t-radio>
              </t-radio-group>
            </td>
          </tr>
        </template>
        <tr v-else>
          <td colspan="3">
            <div class="gl-empty">暂无数据，请配置：授权中心》数据权限</div>
          </td>
        </tr>
      </table>
    </lg-auto-size>
  </edit-container>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { EditContainer } from '@/components';
import api from './api';
import resourceApi from '@/pages/system/auth/dataScope/resourceApi';
import ruleApi from '@/pages/system/auth/dataScope/ruleApi';

const containerRef = ref();
const mainId = ref();
const loading = ref(false);
const resources = ref([]);
const rules = ref([]);

const selection = ref({});

function loadData(id) {
  resources.value = [];
  rules.value = [];
  resourceApi
    .query({ queryType: 'list', pageSize: 99999, $soarQuery: { 'disabled-eq': false, fields: 'id,name' } })
    .then((res) => {
      resources.value = res.list.map((x) => ({ id: x.id, name: x.name }));
      ruleApi
        .query({
          queryType: 'list',
          pageSize: 99999,
          $soarQuery: { 'defaulted-eq': false },
        })
        .then((res) => {
          res.list = res.list.map((x) => ({ id: x.id, name: x.name, resourceId: x.resourceId }));
          const map = {};
          for (const x of res.list) {
            if (!map[x.resourceId]) {
              map[x.resourceId] = [];
            }
            map[x.resourceId].push(x);
            if (x.resourceId === '0') {
              rules.value.push(x);
            }
          }
          const cs = map['0'] || [];
          for (const p of resources.value) {
            p.rules = res.list.filter((r) => r.resourceId === p.id || r.resourceId === '0');
            const rules = map[p.id] || [];
            p.rules = cs
              .filter((y: { name: any }) => rules.findIndex((z: { name: any }) => z.name === y.name) === -1)
              .concat(rules);
          }
        });
    });
  api.getDataScope(id).then((res) => {
    const map = {};
    for (const x of res) {
      map[x.resourceId] = x.ruleId;
    }
    selection.value = map;
  });
}

function submit() {
  const params = [];
  for (const resourceId in selection.value) {
    const ruleId = selection.value[resourceId];
    if (ruleId) {
      params.push({ resourceId, ruleId });
    }
  }
  api
    .setDataScope({
      roleIds: [mainId.value],
      dataScopes: params,
    })
    .then(() => {
      containerRef.value.close();
    })
    .finally(() => {
      loading.value = false;
    });
  loading.value = true;
}

function setAll(e) {
  const { name, id } = e;
  const map = {};
  resources.value.forEach((x) => {
    if (x.rules?.findIndex((r) => r.name === name) !== -1) {
      map[x.id] = id;
    }
  });
  selection.value = map;
}

defineExpose({
  open(id) {
    mainId.value = id;
    loadData(id);
    containerRef.value.open();
  },
});
</script>
<style lang="less" scoped>
.active {
  background-color: var(--td-brand-color-1);
  color: var(--app-color-primary);
}
:deep(.t-list-item) {
  cursor: pointer;
  .t-list-item__action {
    display: none;
  }
  &:hover {
    .t-list-item__action {
      display: unset;
    }
  }
}
:deep(.t-space-item) {
  flex: 1;
}
</style>
